package cc.yihy.storage.qiniu;

import cc.yihy.storage.StorageClient;
import cc.yihy.storage.qiniu.bean.SimpleQiniuClient;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Yihy
 * @version V1.0
 * @Package cc.yihy.storage
 * @Description:
 * @date 2017/6/27 15:29
 */

@Configuration
@ConditionalOnClass({Auth.class, UploadManager.class})
@EnableConfigurationProperties(value = QiniuProperties.class)
public class QiniuAutoConfiguration {

    @Autowired
    private QiniuProperties qiniuProperties;

    @Bean
    @ConditionalOnMissingBean
    public Auth getAuth() {
        return Auth.create(qiniuProperties.getAccessKey(), qiniuProperties.getSecretKey());
    }

    @Bean
    @ConditionalOnMissingBean
    public Zone zone() {
        Zone zone;
        switch (qiniuProperties.getZone()) {
            case "zone0":
                zone = Zone.zone0();
                break;
            case "zone1":
                zone = Zone.zone1();
                break;
            case "zone2":
                zone = Zone.zone2();
                break;
            case "zoneNa0":
                zone = Zone.zoneNa0();
                break;
            default:
                zone = Zone.autoZone();
                break;
        }

        return zone;
    }

    @Bean
    @ConditionalOnMissingBean
    public com.qiniu.storage.Configuration configuration(Zone zone) {
        com.qiniu.storage.Configuration cfg = new com.qiniu.storage.Configuration(zone);

        return cfg;
    }

    @Bean
    @ConditionalOnMissingBean
    public UploadManager uploadManager(com.qiniu.storage.Configuration cfg) {

        UploadManager uploadManager = new UploadManager(cfg);

        return uploadManager;
    }

    @Bean
    @ConditionalOnMissingBean
    public BucketManager bucketManager(Auth auth, com.qiniu.storage.Configuration cfg) {
        BucketManager bucketManager = new BucketManager(auth, cfg);
        return bucketManager;
    }


    @Bean
    @ConditionalOnMissingBean
    public StorageClient qiniuFileClient(Auth auth, UploadManager uploadManager,
                                         BucketManager bucketManager) {
        SimpleQiniuClient qiniuClient = new SimpleQiniuClient(auth, qiniuProperties.getBucketname());
        qiniuClient.setUploadManager(uploadManager);
        qiniuClient.setBucketManager(bucketManager);
        qiniuClient.setDomain(qiniuProperties.getDomain());
        return qiniuClient;
    }
}


